package com.study.hot.jetpack.databinding

import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.os.Handler
import android.view.View
import android.widget.Button
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.*
import com.bumptech.glide.Glide
import com.study.hot.BR
import com.study.hot.R
import com.study.hot.databinding.*
import com.study.hot.jetpack.databinding.model.ImageBean
import com.study.hot.jetpack.databinding.model.User
import com.study.hot.jetpack.databinding.recyclerview.MyListChangeCallback
import com.study.hot.jetpack.databinding.recyclerview.UserAdapter
import kotlinx.android.synthetic.main.activity_mvvm_binding_adapter.*
import kotlinx.android.synthetic.main.activity_mvvm_collection_res.*
import kotlinx.android.synthetic.main.activity_mvvm_include_viewstub.*
import kotlinx.android.synthetic.main.activity_mvvm_recyclerview.*
import kotlinx.android.synthetic.main.activity_mvvm_twoway_bind.*
import org.jetbrains.anko.sdk27.coroutines.onClick
import org.jetbrains.anko.toast
import kotlin.random.Random


/**
 * <pre>
 *     author : fauks
 *     time   : 2020/03/12
 *     desc   :
 * </pre>
 */
class MvvmActivity : AppCompatActivity() {

    private lateinit var user: User

    private val handler = Handler()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //bindProps()
        //twoWayBind()
        //bindEvent()
        //bindMethod()
        //useIncludeAndViewStub()
        //testBindingAdapter()
        //testBindingConversion()
        //testCollectionAndRes()
        //withRecyclerView()
        withRecyclerViewUpdate()
    }

    //-------------------------实战：应用RecyclerView-------------------------
    private val obList = ObservableArrayList<User>()

    //使用ObservableArrayList实现高效刷新
    private fun withRecyclerViewUpdate() {
        setContentView(R.layout.activity_mvvm_recyclerview)
        obList.add(User("fauks", "123"))
        obList.add(User("slx", "456"))
        obList.add(User("mg", "789"))
        val userAdapter = com.study.hot.jetpack.databinding.recyclerview.UserAdapter(obList)
        obList.addOnListChangedCallback(MyListChangeCallback<User>(userAdapter))
        mvvmRv.adapter = userAdapter
    }

    //添加一条数据
    fun addUser(view: View) {
        obList.add(0, User("新数据", "aaa"))
    }

    //添加多条数据
    fun addUsers(view: View) {
        val newDatas = mutableListOf<User>(
                User("新数据1", "aaa1"),
                User("新数据2", "aaa2"),
                User("新数据3", "aaa3"),
                User("新数据4", "aaa4")
        )
        obList.addAll(0, newDatas)
    }

    //删除一条数据
    fun deleteUser(view: View) {
        obList.removeAt(2)
    }

    //更新一条数据
    fun update(view: View) {
        val user = obList[1]
        user.name = "update user"
    }


    //基本使用
    private val userList = arrayListOf<User>()
    private fun withRecyclerView() {
        setContentView(R.layout.activity_mvvm_recyclerview)
        userList.add(User("fauks", "123"))
        userList.add(User("slx", "456"))
        userList.add(User("mg", "789"))
        val userAdapter = com.study.hot.jetpack.databinding.recyclerview.UserAdapter(userList)
        mvvmRv.adapter = userAdapter
    }

    //-------------------------集合、资源绑定-------------------------
    private fun testCollectionAndRes() {
        val binding = DataBindingUtil.setContentView<ActivityMvvmCollectionResBinding>(this, R.layout.activity_mvvm_collection_res)
        val map = ObservableArrayMap<String, String>()
        map["name"] = "fauks"

        val list = ObservableArrayList<String>()
        list.add("a")

        binding.map = map
        binding.list = list
        binding.key = "name"
        binding.index = 0

        changeDataTv.onClick {
            map["name"] = "slx"
            list.add(0, "aaaa")
        }
    }

    object Inner {
        //----BindingConversion
        @JvmStatic
        @BindingConversion
        fun conversionStrToColor(color: String): Int = when (color) {
            "blue" -> Color.parseColor("#0000FF")
            "red" -> Color.parseColor("#FF0000")
            else -> Color.parseColor("#FFFFFF")
        }

        @JvmStatic
        @BindingConversion
        fun conversionStrToDrawable(color: String): Drawable = when (color) {
            "blue" -> ColorDrawable(Color.parseColor("#0000FF"))
            "red" -> ColorDrawable(Color.parseColor("#FF0000"))
            else -> ColorDrawable(Color.parseColor("#FFFFFF"))
        }

        //----BindingAdapter
        //自定义属性
        @JvmStatic
        @BindingAdapter("url")
        fun bindUrl(imageView: ImageView, url: String) {
            Glide.with(imageView.context).load(url).into(imageView)
        }

        //对View原有属性扩展,使用@{}绑定的text属性都会添加-bind后缀
        @JvmStatic
        @BindingAdapter("android:text")
        fun bindText(button: Button, text: String) {
            button.text = "${text}-bind"
        }
    }

    //-------------------------BindingConversion属性、类型转换-------------------------
    private fun testBindingConversion() {
        val binding = DataBindingUtil.setContentView<ActivityMvvmBindingConversionBinding>(this, R.layout.activity_mvvm_binding_conversion)
    }

    //-------------------------使用BindingAdapter-------------------------
    private fun testBindingAdapter() {
        val includeViewstubBinding = DataBindingUtil.setContentView<ActivityMvvmBindingAdapterBinding>(this, R.layout.activity_mvvm_binding_adapter)
        val imageBean = ImageBean()
        imageBean.url = ObservableField("https://www.baidu.com/img/bd_logo1.png?where=super")
        //includeViewstubBinding.image = imageBean


        changeImageBtn.onClick {
            imageBean.url.set("https://img.alicdn.com/imgextra/i3/761686079/TB25Oysr4GYBuNjy0FnXXX5lpXa_!!761686079.jpg_180x180xzq90.jpg_.webp")
        }
    }

    //-------------------------在include和ViewStub中使用MVVM-------------------------
    private fun useIncludeAndViewStub() {
        val includeViewstubBinding = DataBindingUtil.setContentView<ActivityMvvmIncludeViewstubBinding>(this, R.layout.activity_mvvm_include_viewstub)
        user = User()
        user.name = "include"
        includeViewstubBinding.user = user

        includeViewstubBinding.userVs.viewStub?.setOnInflateListener { _, inflated ->
            val vsBind = DataBindingUtil.bind<ViewstubMvvmBinding>(inflated)
            val vsUser = User()
            vsUser.name = "viewStub"
            vsBind?.user = vsUser
        }

        userVs.inflate()
    }

    //-------------------------使用类方法、运算符-------------------------
    private fun bindMethod() {
        val binding = DataBindingUtil.setContentView<ActivityMvvmMethodBinding>(this, R.layout.activity_mvvm_method)
        user = User()
        user.name = "abcde"
        user.isShow = false
        binding.user = user
    }

    //-------------------------事件绑定-------------------------
    //绑定事件与类中方法签名要一一致
    inner class EventHandler {
        fun changeNameAndPassword() {
            user.name = "name:${Random.nextInt(100)}"
            user.password = "password:${Random.nextInt(100)}"
        }
    }

    private fun bindEvent() {
        val binding = DataBindingUtil.setContentView<ActivityMvvmTwowayBindBinding>(this, R.layout.activity_mvvm_twoway_bind)
        user = User()
        binding.user = user
        //binding.eventHandler = EventHandler()
    }

    //-------------------------双向绑定:@={user.name}-------------------------
    private fun twoWayBind() {
        val binding = DataBindingUtil.setContentView<ActivityMvvmTwowayBindBinding>(this, R.layout.activity_mvvm_twoway_bind)
        user = User()
        binding.user = user

        submitTv.onClick {
            toast(user.toString())
        }

        updateTv.onClick {
            user.name = "slx"
            user.password = "abcd"
        }
    }

    //-------------------------属性单向绑定@{user.name}：数据改变视图也改变-------------------------
    private fun bindProps() {
        val binding = DataBindingUtil.setContentView<ActivityMvvmPropsBinding>(this, R.layout.activity_mvvm_props)
        user = User("fauks", "12", "https://www.baidu.com/img/bd_logo1.png?where=super")
        binding.user = user

        //model属性值改变监听
        user.addOnPropertyChangedCallback(object : Observable.OnPropertyChangedCallback() {
            override fun onPropertyChanged(sender: Observable?, propertyId: Int) {
                if (propertyId == BR.name) {
                    toast("name值改变")
                }
            }
        })

        handler.postDelayed({
            user.name = "孙凌霄"
            user.password = "aaaa"
            user.avatar = "https://img14.360buyimg.com/mobilecms/s280x280_jfs/t1/103374/29/14538/46397/5e65a852E5b37a084/8ed5608058d78ec9.jpg.webp"
        }, 2000)
    }

}